package com.test5.liang.login;

import com.test5.liang.config.MyPasswordEncoder;
import com.test5.liang.dao.UserMapper;
import com.test5.liang.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    MyPasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println("进入loadUserByUsername");
        System.out.println("username"+username);
        User user = userMapper.findUserByName(username);
        System.out.println(user);

        if (user == null) {
            return null;
        }
        Collection<GrantedAuthority> authorities = new ArrayList<>();
        String roleName = user.getUserRole()==1?"user":"admin";
        if ("admin".equals(roleName)) {
            authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
        } else  {
            authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
        }
        org.springframework.security.core.userdetails.User userdetail = new org.springframework.security.core.userdetails.User(user.getUserName(),passwordEncoder.encode(user.getPassword()),authorities);
        System.out.println("管理员信息："+user.getUserName()+"   "+passwordEncoder.encode(user.getPassword())+"  "+userdetail.getAuthorities());//通过客户端输入的用户名查询，若数据库有该用户名则查出该用户名对应的Hash密码，然后进行原字符加密(加密后字符不变),与客户端输入密码Hash后比较
        return userdetail;
    }
}

